package com.zmc.admin.infrastructure.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zmc.admin.infrastructure.bean.query.SysUserIdentityQuery;
import com.zmc.admin.infrastructure.entity.SysUserEntity;
import com.zmc.admin.infrastructure.service.SysUserService;
import com.zmc.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zmc.common.utils.PageUtils;
import com.zmc.common.utils.Query;

import com.zmc.admin.infrastructure.dao.SysUserIdentityDao;
import com.zmc.admin.infrastructure.entity.SysUserIdentityEntity;
import com.zmc.admin.infrastructure.service.SysUserIdentityService;


/**
 * @author zmc
 */
@Service("sysUserIdentityService")
public class SysUserIdentityServiceImpl extends ServiceImpl<SysUserIdentityDao, SysUserIdentityEntity> implements SysUserIdentityService {

    @Autowired
    private SysUserService sysUserService;

    @Override
    public PageUtils queryPage(SysUserIdentityQuery query) {
        Page<SysUserIdentityEntity> page = baseMapper.selectPage(new Page<>(query.getPageNum(), query.getPageSize()), getWrapper(query));
        if (page.getTotal() > 0) {
            List<SysUserIdentityEntity> records = page.getRecords();
            List<Long> collect = records.stream().map(SysUserIdentityEntity::getUserId).collect(Collectors.toList());
            List<SysUserEntity> userList = sysUserService.listByIds(collect);
            records.forEach(item -> {
                userList.stream().filter(user -> Objects.equals(user.getUserId(), item.getUserId())).findFirst().ifPresent(user -> {
                    item.setIdentityStatus(user.getIdentityStatus());
                });
            });
        }
        return new PageUtils(page);
    }

    @Override
    public SysUserIdentityEntity getByUserId(Long userId) {
        LambdaQueryWrapper<SysUserIdentityEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserIdentityEntity::getUserId, userId).last(" limit 1");
        return getOne(wrapper);
    }

    public LambdaQueryWrapper<SysUserIdentityEntity> getWrapper(SysUserIdentityQuery query) {
        LambdaQueryWrapper<SysUserIdentityEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.isNotEmpty(query.getRealName()), SysUserIdentityEntity::getRealName, query.getRealName())
                .eq(StringUtils.isNotEmpty(query.getPayAccount()), SysUserIdentityEntity::getPayAccount, query.getPayAccount());
        return wrapper;
    }

}